package async;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author huangkunming
 * 多路复用非阻塞-客户端请求
 */
public class AsyncHttpClientDemo {

    public static void main(String[] args) {
        CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
        httpClient.start();

        HttpGet request = new HttpGet("https://www.shoplus.net/api/v1/product/categories");

        final CountDownLatch latch = new CountDownLatch(1);

        httpClient.execute(request, new FutureCallback<HttpResponse>() {
            @Override
            public void completed(HttpResponse response) {
                // 处理响应结果
                try {
                    System.out.println("Response: " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
                } finally {
                    latch.countDown();
                }
            }

            @Override
            public void failed(Exception ex) {
                // 处理请求失败
                ex.printStackTrace();
                latch.countDown();
            }

            @Override
            public void cancelled() {
                // 处理请求取消
                latch.countDown();
            }
        });

        System.out.println("主线程继续执行....");

        try {
            // 等待请求完成（这里只是示例，实际应用中可能会有更复杂的逻辑来等待结果）
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
